package com.baihui.crm;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;

public class UpdateRecords {
    public static void main(String a[]) {
        try {
            //----------------------------Fetch Ticket ----------------------
            String ticket = getIAMTicket("ZohoCRM", "350514064_taobao", "351441");
            String apikey = "YJEA9bFjnsamo0hVAXt4aVyEsYOK704f"; //your API key
//          String ticket = getIAMTicket("BaihuiCRM", "691035070_taobao", "382475");
//          String apikey = "EeoK0FLD7FGzKu7hWOKBCT5d9NgZPHG-"; //your API key
            String newFormat = "1";

            String targetURL = "https://crm.baihui.com/crm/private/xml/Contacts/updateRecords";
//            String targetURL = "https://crm.baihui.com/crm/private/xml/Leads/insertRecords";
            String paramname = "content";
//            String xmlDataString = "<SalesOrders><row no='1'><FL val=\"Billing Code\"><![CDATA[510000]]></FL><FL val=\"Discount\">1.0</FL><FL val=\"Grand Total\">26.0</FL><FL val=\"收件人电话\"><![CDATA[13556171156]]></FL><FL val=\"收货确认时间\">2012-02-28 13:16:13</FL><FL val=\"运单号码\"><![CDATA[1900119259211]]></FL><FL val=\"Subject\"><![CDATA[英国贝儿欣 宽口径恩美奶嘴0-4个月/慢流量 2个装 BD4030]]></FL><FL val=\"Sub Total\">27.0</FL><FL val=\"付款时间\">2012-02-16 16:58:59</FL><FL val=\"买家留言\">null</FL><FL val=\"发货方式\"><![CDATA[快递]]></FL><FL val=\"Billing Street\"><![CDATA[南洲北路尚东峰景A2-302]]></FL><FL val=\"Billing State\"><![CDATA[广东省]]></FL><FL val=\"Status\"><![CDATA[交易成功]]></FL><FL val=\"成交时间(拍下时间)\">2012-02-16 16:58:37</FL><FL val=\"Billing City\"><![CDATA[广州市 海珠区]]></FL><FL val=\"Billing Country\"><![CDATA[中国]]></FL><FL val=\"CONTACTID\"><![CDATA[33403000000218287]]></FL><FL val=\"Contact Name\"><![CDATA[美白祛斑专家99]]></FL><FL val=\"物流公司\"><![CDATA[韵达快运]]></FL><FL val=\"Adjustment\">0.0</FL><FL val=\"运费\">8.0</FL><FL val=\"Due Date\">null</FL><FL val=\"Tax\">0</FL><FL val=\"Description\">null</FL><FL val=\"Product Details\"><product no=\"1\"><FL val=\"Total\">27.0</FL><FL val=\"Product Id\"><![CDATA[33403000000035139]]></FL><FL val=\"Net Total\">26.0</FL><FL val=\"Total After Discount\">26.0</FL><FL val=\"Discount\">1.0</FL><FL val=\"Tax\">0</FL><FL val=\"Quantity\">1</FL><FL val=\"Product Name\"><![CDATA[英国贝儿欣 宽口径恩美奶嘴0-4个月/慢流量 2个装 BD4030]]></FL><FL val=\"Product Description\">null</FL><FL val=\"List Price\">27.0</FL></product></FL></row></SalesOrders>";
            
            String xmlDataString = "<Contacts><row no='1'><FL val=\"性别\"><![CDATA[]]></FL><FL val=\"昵称\"><![CDATA[wsy18256738386]]></FL><FL val=\"Mobile\"><![CDATA[18256738386]]></FL><FL val=\"Last Name\"><![CDATA[wsy18256738386]]></FL><FL val=\"上次登陆时间\">2012-03-22 21:37:54</FL><FL val=\"买家指数\">1</FL><FL val=\"Mailing State\"><![CDATA[安徽省]]></FL><FL val=\"星座\"><![CDATA[]]></FL><FL val=\"Mailing Street\"><![CDATA[亳州职业技术学院]]></FL><FL val=\"Date of Birth\">null</FL><FL val=\"淘宝会员\"><![CDATA[普通会员]]></FL><FL val=\"买家好评率\">100</FL><FL val=\"Mailing Country\"><![CDATA[中国]]></FL><FL val=\"卖家好评率\">0</FL><FL val=\"Phone\"><![CDATA[]]></FL><FL val=\"真实姓名\"><![CDATA[王沈阳]]></FL><FL val=\"年龄\">0</FL><FL val=\"Mailing Zip\"><![CDATA[236800]]></FL><FL val=\"注册时间\">2012-01-11 10:42:20</FL><FL val=\"客户所在地\">null</FL><FL val=\"卖家指数\">0</FL><FL val=\"Mailing City\"><![CDATA[亳州市-谯城区]]></FL><FL val=\"Email\">null</FL><FL val=\"成交订单数\">0</FL><FL val=\"累计消费金额\">100</FL><FL val=\"最后一笔成交时间\">2012-03-17 10:55:10</FL><FL val=\"用户状态\">活跃</FL><FL val=\"休眠时间\">60</FL></row></Contacts>";
//            System.out.println(xmlDataString.length());
            
            class UTF8PostMethod extends PostMethod {
                public UTF8PostMethod(String url) {
                    super(url);
                }

                @Override
                public String getRequestCharSet() {
                    return "UTF-8";
                }
            }
            UTF8PostMethod post = new UTF8PostMethod(targetURL);
            post.setParameter("ticket", ticket);
            post.setParameter("apikey", apikey);
            post.setParameter("newFormat", newFormat);
            post.setParameter("xmlData", xmlDataString);
            post.setParameter("wfTrigger", "true");
            post.setParameter("id", "34177000000072039");
            
            HttpClient httpclient = new HttpClient();
            PrintWriter myout = null;


            // Execute http request
            try {
                long t1 = System.currentTimeMillis();
                Date date = new Date();
                SimpleDateFormat f= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                System.out.println(f.format(date));
                System.out.println("postpostpostpostpost=" + post);
                int result = httpclient.executeMethod(post);
                System.out.println(">> Time taken " + (System.currentTimeMillis() - t1));
                System.out.println("HTTP Response status code: " + result);

                // writing the response to a file
                myout = new PrintWriter(new File("response.xml"));
                myout.print(post.getResponseBodyAsString());

                //------------Get response as a string ----------
                String postResp = post.getResponseBodyAsString();
                System.out.println("postResp=======>" + postResp);
                
                
                
                String getDateURL = "https://crm.baihui.com/crm/private/xml/SalesOrders/getMyRecords";
                
                PostMethod getdatepost = new PostMethod(getDateURL);
                getdatepost.setParameter("ticket",ticket);
                getdatepost.setParameter("apikey", apikey);
                getdatepost.setParameter("newFormat", newFormat);
                getdatepost.setParameter("selectColumns", "SalesOrders(all)");
                getdatepost.setParameter("lastModifiedTime", f.format(date));
                int result1 = httpclient.executeMethod(getdatepost);
                System.out.println("HTTP Response status code: " + result1);
                myout = new PrintWriter(new File("response.xml"));
                myout.print(getdatepost.getResponseBodyAsString());

                //------------Get response as a string ----------
                String postResp1 = getdatepost.getResponseBodyAsString();
                System.out.println("postResp1=======>" + postResp1);
                
                
                
//             	Map objectMap = new HashMap();
//            	JSONObject jb = JSONObject.fromObject(postResp1);
//            	JSONObject ja = jb.getJSONObject("response").getJSONObject("result");  
//            	JSONArray orderDetailArr = ja.getJSONObject("SalesOrders").getJSONArray("row");  
//            	 for(int j=0;j<orderDetailArr.size();j++){   
//            		 if(orderDetailArr.get(j) != null){
////            			 objectMap.put(orderDetailArr.get(j), value)
//            		 }
//                 }
            	 
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                myout.close();
                post.releaseConnection();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //------------------------------------Get IAM Ticket ---------------------------------
    public static String getIAMTicket(String serviceName, String loginId, String password) {
        String strTicket = null;
        try {

            String iamUrl = "https://i.baihui.com/login?servicename=" + serviceName + "&FROM_AGENT=true&LOGIN_ID=" + loginId + "&PASSWORD=" + password;
            URL u = new URL(iamUrl);
            HttpURLConnection c = (HttpURLConnection) u.openConnection();
            InputStream in = c.getInputStream();
            InputStreamReader ir = new InputStreamReader(in);
            BufferedReader br = new BufferedReader(ir);

            String strLine = null;

            while ((strLine = br.readLine()) != null) {
                if (strLine != null && strLine.startsWith("TICKET")) {
                    strTicket = strLine.substring(7);
                }
            }

            in.close();
        } catch (Exception e) {
            e.printStackTrace();

        }
        return strTicket;
    }
}
